﻿using System;
using System.ComponentModel;
using System.Windows;
using Collab.Modules.ContactBrowser.Commands;
using Collab.Services.Remote.WebserviceProxy;

namespace Collab.Modules.ContactBrowser.ViewModel
{
    public class LoginViewModel : ViewModel
    {

        private readonly IRepository repository;
        private readonly MainViewModel mainViewModel;
        
        /// <summary>
        /// Gets or sets the username.
        /// </summary>
        /// <value>The username.</value>
        public string Username { get; set; }
        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        public string Password { get; set; }

        /// <summary>
        /// Gets or sets the login command.
        /// </summary>
        /// <value>The login command.</value>
        public LoginCommand LoginCommand { get; set; }

        public LoginViewModel(IRepository repository, MainViewModel mainViewModel)
        {
            this.repository = repository;
            this.mainViewModel = mainViewModel;
            this.LoginCommand = new LoginCommand(this);
        }

        public void Login()
        {
            var bw = new BackgroundWorker();
            this.LoginCommand.CanLogin = false;

            bw.DoWork += delegate(object o, DoWorkEventArgs de)
            {
                try
                {
                    bool isAuthenticated = this.repository.AuthenticateUser(Username, Password);

                    if (!isAuthenticated)
                        MessageBox.Show("Wrong credentials");

                    else
                        this.mainViewModel.NavigateToContactsView(Username);
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(String.Format("Unable to login.\n\nMessage: {0}", ex.Message));
                }
                finally
                {
                    this.LoginCommand.CanLogin = true;
                }
            };

            bw.RunWorkerAsync();
        }

    }
}
